package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    /**
     * 新增菜品
     * @param dish
     */
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Override
    public void addDish(DishDTO dish) {
        //把前端接收到的数据重新赋值给实体类
        Dish dishEntity = new Dish();
        BeanUtils.copyProperties(dish,dishEntity);
        //新增菜品默认为停售状态，需要手动进行启售
        dishEntity.setStatus(StatusConstant.DISABLE);
        //因为一些公共字段我们已经实现AOP提前赋值，这里我们就不用在重新赋值
        //添加菜品
        dishMapper.addDish(dishEntity);
        //获取添加成功的ID
        Long id = dishEntity.getId();
        //遍历前端传进来的口味
        List<DishFlavor> flavors = dish.getFlavors();
        if (flavors.size() > 0) {
            flavors.forEach(flavor -> {
                 flavor.setDishId(id);
            });
            //向口味表里插入数据
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    @Transactional
    public PageResult pageSelectDish(DishPageQueryDTO dishPageQueryDTO) {
        //用第三方工具进行分页
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        //创建时间的倒序排列，单页最多显示10条
        Page<DishVO> dishes = dishMapper.pageSelectDish(dishPageQueryDTO);
        //用PageResult返回给前端
        return new PageResult(dishes.getTotal(),dishes.getResult());
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */

    @Override
    public DishVO selectByIdDish(Integer id) {
        Dish dish = dishMapper.selectByIdDish(id);
        //查询id的口味
        List<DishFlavor> flavor = dishFlavorMapper.selectFlavor(id);

        DishVO dishVo = new DishVO();
        BeanUtils.copyProperties(dish, dishVo);
        dishVo.setFlavors(flavor);
        return dishVo;
    }

    /**
     * 分类查询
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Integer categoryId) {
        List<Dish> dish = dishMapper.list(categoryId);
        return dish;
    }

    /**
     * 菜品修该状态
     * @param status
     * @param id
     */
    @Override
    public void updateStatusDish(Integer status, Integer id) {
        Dish dish = new Dish();
        dish.setId(id.longValue());
        dish.setStatus(status);
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dishMapper.updateStatusDish(dish);
    }

    /**
     * 删除菜品
     * @param ids
     */
    @Override
    public void deleteDish(List<Integer> ids) {
        //进行判断被套餐关联的菜品不能删除
        //根据id去查套餐
        ids.forEach(id ->{
            Integer count = setmealMapper.countByCategoryId(id.longValue());
            if (count > 0){
                throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
            }
        });
        //在售状态下，不可删除菜品
        //根据ID去查询菜品状态
        ids.forEach(id -> {
            Dish dish = dishMapper.selectByIdDish(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        //都满足可以进行删除,删除菜品后口味也要进行删除
        dishMapper.deleteDish(ids);
        dishFlavorMapper.deleteByFlavor(ids);

    }

    /**
     * 修改菜品数据
     * @param dishDTO
     */
    @Override
    @Transactional
    public void updateDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //添加修该的时间
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        //修改数据表
        dishMapper.updateStatusDish(dish);
        //获取传进来的口味数据和要修改的id
        Long id = dishDTO.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors.size() > 0) {
            //根据id把之前的口味数据删除重新添加
            List<Integer> list = new ArrayList<>();
            list.add(id.intValue());
            dishFlavorMapper.deleteByFlavor(list);
            //删除后重新添加
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(id);
            });

            dishFlavorMapper.insertBatch(flavors);
        }
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish.getCategoryId().intValue());

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectFlavor(d.getId().intValue());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }


}
